import React,{useState,useRef,useEffect} from 'react'
import type { CSSProperties,ReactNode } from 'react'
interface MylazyLoadProps {
    className?: string,
    style?: CSSProperties,
    placeholder?: ReactNode,
    offset?:number,
    width?:number,
    height?:number,
    onContentVisible?:()=>void,
    children: ReactNode,
}
export default function MyLazyLoad(props: MylazyLoadProps) {
    const elementObserver = useRef<IntersectionObserver>()
    const contentRef = useRef<HTMLDivElement>(null)
    const {
        className='',
        style,
        placeholder,
        offset=0,
        width,
        height,
        onContentVisible,
        children,
    } = props
    const [visible,setVisible] = useState(false)
    function lazyloadHandler(entries:IntersectionObserverEntry[]){
        const [entry] = entries
        if(entry.isIntersecting){
            setVisible(true)
            onContentVisible?.()
            elementObserver.current?.disconnect()
        }
    }
    useEffect(()=>{
        const options={
            rootMargin:`${offset}px`,
            threshold:0,
        }
        elementObserver.current = new IntersectionObserver(lazyloadHandler,options)
        const node = contentRef.current
        if(node){
            elementObserver.current?.observe(node)
        }
    },[])
  return (
    <div ref={contentRef} className={className} style={style}>
        {visible?children:placeholder}     
    </div>
  )
}
